package com.hs.srm.admin.modules.requisition.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hs.srm.admin.common.util.OANoticeUtil;
import com.hs.srm.admin.modules.requisition.dao.NproPurchRequestItemDao;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.NproPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.vo.SupplyGoodsEntityVO;
import com.hs.srm.base.common.annotation.DataFilter;
import com.hs.srm.base.common.utils.Constant;
import com.hs.srm.base.common.utils.QueryParam;
import com.hs.srm.common.utils.PageUtils;
import com.landray.kmss.km.review.webservice.Exception_Exception;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author yanfei
 * @date 2019年4月29日
 */
@Service("nproPurchRequestItemService")
public class NproPurchRequestItemServiceImpl extends ServiceImpl<NproPurchRequestItemDao, NproPurchRequestItemEntity> implements NproPurchRequestItemService {

    @Autowired
    private NproPurchRequestHeaderService nproPurchRequestHeaderService;

    @Autowired
    private NproPurchRequestItemDao nproPurchRequestItemDao;

    @Override
    @DataFilter
    public PageUtils queryPage(Map<String, Object> params) {
        // 从列表页面获取对应的值
        String purchRequestCode = (String) params.get("purchRequestCode");//采购申请单号
        String requestDate = (String) params.get("requestDate");//需求日期
        String deliveryDate = (String) params.get("deliveryDate");//交期
        String costCenter = (String) params.get("costCenter");//成本中心
        String purchGroup = (String) params.get("purchGroup");//采购组
        Page<NproPurchRequestItemEntity> page = this.selectPage(
                new QueryParam<NproPurchRequestItemEntity>(params).getPage(),
                new EntityWrapper<NproPurchRequestItemEntity>()
                        .like(StringUtils.isNotBlank(purchRequestCode), "purch_request_code", purchRequestCode)
                        .like(StringUtils.isNotBlank(costCenter), "cost_center", costCenter)
                        .like(StringUtils.isNotBlank(requestDate), "request_date", requestDate)
                        .like(StringUtils.isNotBlank(deliveryDate), "delivery_date", deliveryDate)
                        .like(StringUtils.isNotBlank(purchGroup), "purch_group", purchGroup)
                        .orderBy("purch_request_code", false)
                        .addFilterIfNeed(!ObjectUtils.isEmpty(params.get(Constant.SQL_FILTER)),
                                (String) params.get(Constant.SQL_FILTER)));
        return new PageUtils(page);
    }


    @Override
    public NproPurchRequestItemEntity selectById(String pkId) {

        return this.baseMapper.selectById(pkId);
    }

    @Override
    public List<Map<String, String>> selectUserMapList(List<String> ids) {

        return this.baseMapper.selectUserMapList(ids);
    }

    @Override
    public List<NproPurchRequestItemEntity> selectBatchIds(List<String> ids) {
        return this.baseMapper.selectBatchIds(ids);
    }

    @Override
    public List<NproPurchRequestItemEntity> selectRequestItem() {

        return this.nproPurchRequestItemDao.selectRequestItem();
    }

    //自定义分页
    @Override
    public PageUtils selectDetailPage(Map<String, Object> params) {
        Page<NproPurchRequestItemEntity> page = this.selectDetailPage(
                new QueryParam<NproPurchRequestItemEntity>(params).getPage(), new EntityWrapper<NproPurchRequestItemEntity>(),
                params);
        return new PageUtils(page);
    }

    private Page<NproPurchRequestItemEntity> selectDetailPage(Page<NproPurchRequestItemEntity> page,
                                                              Wrapper<NproPurchRequestItemEntity> wrapper, Map<String, Object> params) {
        page.setRecords(this.nproPurchRequestItemDao.selectDetailPage(page, wrapper, params));
        return page;
    }

    @Override
    public List<SupplyGoodsEntityVO> findById(ArrayList<String> idsarrayList) {

        return this.baseMapper.findById(idsarrayList);
    }

    @Override
    public List<NproPurchRequestItemEntity> findByNo(
            String purchRequestCode, List<String> ids) {

        return this.baseMapper.findByNo(purchRequestCode, ids);
    }

    //改变货源状态
    @Override
    public boolean changeGoodsStatus(int goodsStatus, String npkId) {
        NproPurchRequestItemEntity itemEntity = new NproPurchRequestItemEntity();
        itemEntity.setGoodsStatus(goodsStatus);
        itemEntity.setPkId(npkId);
        int row = this.baseMapper.updateById(itemEntity);
        return row > 0 ? true : false;
    }

    @Override
    public NproPurchRequestItemEntity findbypkId(String pkid) {
        return this.baseMapper.findbypkId(pkid);
    }

    @Override
    public void updateAll(NproPurchRequestItemEntity nproPurchRequestItemEntity) {
        this.baseMapper.updateById(nproPurchRequestItemEntity);
    }

    /**
     * 通过请购编码、请购行项目编码将请购单恢复草稿状态
     *
     * @param requestCode
     * @param purchRequestItemCode
     */
    @Override
    public void updateStatus(String requestCode, String purchRequestItemCode) {
        this.baseMapper.updateStatus(requestCode, purchRequestItemCode);
    }

    /**
     * 删除非生产性请购单
     *
     * @param pkIds
     * @param requestCode
     * @param reason
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String deleteRequisition(String[] pkIds, String requestCode, String reason) throws Exception_Exception {
        //先判断当前用户OA账号是否为空，下单人OA账号是否为空
        String msg = OANoticeUtil.isOAccountBlank(requestCode);
        if (StringUtils.isNotBlank(msg)) {
            return msg;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("purch_request_code", requestCode);
        //同一请购编码下所有的请购明细
        List<NproPurchRequestItemEntity> itemEntities = nproPurchRequestItemDao.selectByMap(map);

        //选中要删除的请购明细
        List<NproPurchRequestItemEntity> deleteItems = nproPurchRequestItemDao.selectBatchIds(Stream.of(pkIds).collect(Collectors.toList()));

        //删除选中的明细,逻辑删除
        deleteItems.forEach(item -> item.setDeleteFlag("1"));
        deleteItems.forEach(item -> nproPurchRequestItemDao.updateById(item));

        //删除订单后OA通知下单人,下单人OA账号存放在header表中，先通知再判断是否删除头信息
        //退单理由前添加物料描述，提醒下单人哪个请购单被退单了
        //目前是只能一条一条明细进行退单删除，后续修改这里也要做修改,循环遍历
        reason = deleteItems.get(0).getMaterialDesc() + " : " + reason;
        boolean b = OANoticeUtil.remindCreator(requestCode, reason, "采购驳回请购申请单通知！");
        if (!b) {
            return "退单失败！";
        }

        //删除的明细和总的明细数量相同，则删除头信息，逻辑删除
        if (itemEntities.size() == pkIds.length) {
            nproPurchRequestHeaderService.updateByRequestCode(requestCode);
        }

        return "退单成功!";
    }

    /**
     * 根据申请编码和行项目查找申请单
     *
     * @param purchRequestCode
     * @param purchRequestItemCode
     * @return
     */
    @Override
    public NproPurchRequestItemEntity selectNproItem(String purchRequestCode, String purchRequestItemCode) {
        EntityWrapper<NproPurchRequestItemEntity> queryWrapper = new EntityWrapper<>();
        queryWrapper.eq("purch_request_code", purchRequestCode);
        queryWrapper.eq("purch_request_item_code", purchRequestItemCode);
        NproPurchRequestItemEntity one = this.selectOne(queryWrapper);
        if (one != null) {
            return one;
        }
        return null;
    }

}
